package com.zjl.spring.Spring5新特性.Webflux新功能.函数式编程模型;

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromValue;

public class UserLongHandler {
    private final UserLongService userLongService;
    public UserLongHandler(UserLongService userLongService){
        this.userLongService=userLongService;
    }

    public Mono<ServerResponse> getUserLongById(ServerRequest request){
        //获取id
        Long id = Long.valueOf(request.pathVariable("id"));//将获取的字符串转成Long

        //空值判断
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();

        Mono<UserLong> userLongById = this.userLongService.getUserLongById(id);

        //进行数据转换
        /**使用操作符把userMono转换成Mono<ServerResponse>类型,
         *
         * flatMap: flatMap返回一个 新的ono,
         * ok():创建一个将状态设置为200 OK的构建器
         * contentType:设置正文的类型
         * body:将响应的主体设置为给定的BodyInserter并返回
         * switchIfEmpty:如果flatMap返回的是空，就调用空值处理
         *
         */

        return userLongById.flatMap(p->ServerResponse.ok().
                contentType(MediaType.APPLICATION_JSON).
//                body(fromObject(p)).
                body(fromValue(p)).
                switchIfEmpty(notFound)//null判断
        );


    }
    public Mono<ServerResponse> getAllUserLong(ServerRequest request){
        //调用service获取数据
        Flux<UserLong> userLongs = this.userLongService.getAllUserLong();
        //进行数据转换
        return ServerResponse.ok().
                contentType(MediaType.APPLICATION_JSON).
                body(userLongs, UserLong.class);

    }
    public Mono<ServerResponse> setUserLong(ServerRequest request){
        //得到对象
        Mono<UserLong> userLongs=request.bodyToMono(UserLong.class);

        return ServerResponse.ok().
                build(this.userLongService.setUserLong(userLongs));

    }

}
